//
//  RadioViewController.m
//  WWXELuShang
//
//  Created by lanou on 15/12/19.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "RadioViewController.h"
#import "RadioView.h" 
#import "Radio.h"
#import "DetailsTableViewController.h"
#import "BlurImageView.h"
#import "CFDanmakuView.h"
#import "CFDanmakuInfo.h"

@interface RadioViewController ()<CFDanmakuDelegate>{
    CFDanmakuView *_danmakuView;
    CGFloat sliderValue;
    NSTimer *_timer;
    BOOL isDanmakuView;

}

@property (nonatomic,strong)RadioView *radioView;

@property (nonatomic,strong) NSMutableArray *rootArray; //电台数组解析

@property (nonatomic,strong) NSMutableArray *barrageArray; //弹幕的解析


@property (nonatomic,strong) DetailsTableViewController *detailsVC;


@property (nonatomic,assign) CGFloat date;
@property (nonatomic,assign) CGFloat floatQ;
@property (nonatomic,assign) CGFloat floatH;

@property (nonatomic,assign) int index;

@property (nonatomic,strong) CFDanmakuInfo *cfDanmakuInfo;


@end

@implementation RadioViewController
- (void)setUpBack
{
    UIImage *buttonImage = [UIImage imageNamed:@"barrage1"];
    buttonImage = [buttonImage imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
    [self.radioView.barrageButton setImage:buttonImage forState:(UIControlStateNormal)];
    self.radioView.barrageButton.tag = 1000;
}
- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = YES;
    if (_danmakuView) {
        [self setUpBack];
        [self stopDanmu];
    }

}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //模糊视图
    BlurImageView *blurImageView = [[BlurImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview: blurImageView];
    
    
    
    
    self.view.backgroundColor = [UIColor grayColor];
    self.radioView = [[RadioView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    
    self.navigationController.navigationBar.hidden = YES;
    
    
    

    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.frame = CGRectMake(kWidth / 25, kHeight / 24.7, 30, 30);
    [backButton addTarget:self action:@selector(dismissRadio) forControlEvents:(UIControlEventTouchUpInside)];
    [backButton setImage:[UIImage imageNamed:@"arrowdown"] forState:(UIControlStateNormal)];
    [backButton setTintColor:[UIColor whiteColor]];
    
    [self.radioView.detailsButton addTarget:self action:@selector(changeToDetails) forControlEvents:(UIControlEventTouchUpInside)];
   
    
    //接收通知，开始播放我们的歌曲
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(starToPlay) name:@"readyToPlay" object:nil];
    
    
    
    
    
    if ([Radio shareWithRadio].isReadyToPlay == YES) {
        
        self.radioView.playButton.tag = 1;
        [self.radioView.playButton addTarget:self action:@selector(playRadio) forControlEvents:UIControlEventTouchUpInside];
        
    }else{
        self.radioView.playButton.tag = 1000;
        [self.radioView.playButton addTarget:self action:@selector(playRadio) forControlEvents:UIControlEventTouchUpInside];
    }
    
    
    //弹幕
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopDanmu2) name:@"回到后台" object:nil];
    
    
    
    [self.radioView.barrageButton addTarget:self action:@selector(barrageDan) forControlEvents:(UIControlEventTouchUpInside)];
    self.radioView.barrageButton.tag = 1000;
    
    
    
    [self jsonRadio];
    
    [self getHourTime];
    
   
 
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getText) name:@"radio" object:nil];
    
    
    
    
    
    [self.view addSubview:self.radioView];
    [self.radioView addSubview:backButton];

    [self setupDanmakuView];

    [self setBarrage]; //解析弹幕
    
    
    
    
    
   
    
    // Do any additional setup after loading the view.
}
- (void)stopDanmu2{
    NSLog(@"弹幕后台返回");
    
    [_danmakuView stop];
    _danmakuView.delegate = nil;
    [_danmakuView removeFromSuperview];
    isDanmakuView = NO;
    [self setUpBack];
    
    
    
}

- (CGFloat)getHourTime{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"HH.mm"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
 
    self.date = [dateTime floatValue];
    
    return self.date;
    
}

//获取radio名字
- (void)getText{
    self.radioView.albumLabel.text = self.radioView.radio.album;
    self.radioView.programtimeLabel.text = self.radioView.radio.programtime;
    [self.radioView.pictureView setImageWithURL:[NSURL URLWithString:self.radioView.radio.radiopicurl]];
    
    
//    NSLog(@"%@",self.radioView.albumLabel.text);
    
}




//开始播放
- (void)starToPlay{
    [[Radio shareWithRadio]starPlayRadio];
    if ([Radio shareWithRadio].isReadyToPlay == YES) {
        [self.radioView.playButton setImage:[UIImage imageNamed:@"player_pause"] forState:(UIControlStateNormal)];
    }
}

//弹幕
- (void)barrageDan{
    self.radioView.barrageButton.tag += 1;
    int tag = (self.radioView.barrageButton.tag - 1000) % 2;
    if (tag == 1) {
        UIImage *buttonImage = [UIImage imageNamed:@"barrage2"];
        buttonImage = [buttonImage imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
        [self.radioView.barrageButton setImage:buttonImage forState:(UIControlStateNormal)];
        [self postDanmu];
        [Radio shareWithRadio].isReadyToBarrage = NO;


    }else{
        
//        UIImage *buttonImage = [UIImage imageNamed:@"barrage1"];
//        buttonImage = [buttonImage imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
//        [self.radioView.barrageButton setImage:buttonImage forState:(UIControlStateNormal)];
//        [self stopDanmu];
        [self stopDanmu2];
        [Radio shareWithRadio].isReadyToBarrage = YES;


        
    }
    
    
}



//播放
- (void)playRadio{
    self.radioView.playButton.tag += 1;
    int tag = (self.radioView.playButton.tag - 1000) % 2;
    
    if (tag == 0) {
        [self.radioView.playButton setImage:[UIImage imageNamed:@"player_play@2x"] forState:(UIControlStateNormal)];
        [Radio shareWithRadio].isReadyToPlay = NO;
        [[Radio shareWithRadio]stopRadio];
        
    }else{
        
        
        [self.radioView.playButton setImage:[UIImage imageNamed:@"player_pause@2x"] forState:(UIControlStateNormal)];
        [Radio shareWithRadio].isReadyToPlay = YES;
        [[Radio shareWithRadio]starPlayRadio];
        
    }
  
}


//懒加载

- (DetailsTableViewController *)detailsVC{
    if (!_detailsVC) {
        _detailsVC =[[DetailsTableViewController alloc]init];
    }
    return _detailsVC;
}



//跳转详情页面
- (void)changeToDetails{
    
    self.detailsVC.rootArray = self.rootArray;
    
    self.navigationController.navigationBar.hidden = NO;
    
    [self.detailsVC.navigationController.navigationBar setTitleTextAttributes:
     @{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.detailsVC.title = @"电台歌单";
    [self stopDanmu];
    [self barrageDan];
    [self.navigationController pushViewController:self.detailsVC animated:YES];
    
    
}



//返回
- (void)dismissRadio{
    if ([Radio shareWithRadio].isReadyToPlay == YES) {
        [self.radioView.playButton setImage:[UIImage imageNamed:@"player_pause"] forState:(UIControlStateNormal)];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (NSMutableArray *)rootArray{
    if (!_rootArray) {
        _rootArray = [[NSMutableArray alloc]init];
    }
    return _rootArray;
}


//电台的数据解析
- (void)jsonRadio{
    [LORequestManger GET:kRadio success:^(id response) {
        
        NSDictionary *rootDic = (NSDictionary *)response;
        NSDictionary *resultDic = rootDic[@"result"];
        NSArray *listArray = resultDic[@"list"];
        NSString *radioinfourl = resultDic[@"radioinfourl"];
        
        [Radio shareWithRadio].radioinfourl = radioinfourl;
        for (NSDictionary *dic in listArray) {
            Radio *radio = [Radio shareJsonWithDictionary:dic];
            [self.rootArray addObject:radio];
        }
        
        for (int i = 0; i < [self.rootArray count]; i ++) {
            Radio *radio = self.rootArray[i];
            NSString *str = [radio.programtime stringByReplacingOccurrencesOfString:@":" withString:@"."];
            NSString *strQ = [str substringToIndex:5];
            self.floatQ = [strQ floatValue];
            
            NSString *strH = [str substringWithRange:NSMakeRange(8, 5)];
            self.floatH = [strH floatValue];
   
            if (self.date > self.floatQ && self.date < self.floatH) {
                self.index = i;
//                NSLog(@"%d",self.index);
                self.detailsVC.index = self.index;
//                NSLog(@"%d",self.detailsVC.index);
            }
        }
        
        self.radioView.radio = self.rootArray[self.index];
//        NSLog(@"%@",self.radioView.radio);
        
         [[NSNotificationCenter defaultCenter]postNotificationName:@"radio" object:nil];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    
}



- (NSMutableArray *)barrageArray{
    if (!_barrageArray) {
        _barrageArray = [[NSMutableArray alloc]init];
    }
    return _barrageArray;
}



//弹幕的解析
- (void)setBarrage{
    
    [LORequestManger GET:kurl success:^(id response) {
        NSDictionary *rootDic = (NSDictionary *)response;
        NSDictionary *resultDic = rootDic[@"result"];
        NSArray *listArr = resultDic[@"list"];
        for (NSDictionary *dic in listArr) {
            [self.barrageArray addObject:dic[@"content"]];
            [self.barrageArray addObject:dic[@"sourcecontent"]];
        }
//        NSLog(@"%@",self.barrageArray);
//        [self setupDanmakuData];
        //添加弹幕内容
        [_danmakuView setupDanmakuDataWithTextArray:self.barrageArray];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}


- (void)setupDanmakuView{
    CGRect rect =  CGRectMake(50, 40, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)-150);
    _danmakuView = [[CFDanmakuView alloc] initWithFrame:rect];

    [_danmakuView setUpConfiguration];
    isDanmakuView = YES;
    _danmakuView.delegate = self;
    [self.view addSubview:_danmakuView];
    
}

//发送弹幕
- (void)postDanmu{
    if (isDanmakuView == NO) {
        [self setupDanmakuView];
        [_danmakuView setupDanmakuDataWithTextArray:self.barrageArray];
    }
    if (_danmakuView.isPrepared) {
        if (!_timer) {
            _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(onTimeCount) userInfo:nil repeats:YES];
        }
        [_danmakuView start];
        
    }
}

- (CFDanmakuInfo *)cfDanmakuInfo{
    if (!_cfDanmakuInfo) {
        _cfDanmakuInfo = [[CFDanmakuInfo alloc]init];
    }
    return _cfDanmakuInfo;
}


//停止弹幕
- (void)stopDanmu{
    [_danmakuView stop];
    _danmakuView.delegate = nil;
    [_danmakuView removeFromSuperview];
    isDanmakuView = NO;
    
}


- (void)onTimeCount{
    sliderValue += 0.1/120;
    if (sliderValue>120.0) {
        sliderValue=0;
    }
}

- (BOOL)danmakuViewIsBuffering:(CFDanmakuView *)danmakuView{
    return NO;
}

- (NSTimeInterval)danmakuViewGetPlayTime:(CFDanmakuView *)danmakuView{
    if(sliderValue == 1.0) [_danmakuView stop]
        ;
    return sliderValue*120.0;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
